package com.io.压缩20M文件从30秒到1秒的优化过程;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Test4 {
	
	private static final String ZIP_FILE = "D:/zsl/2.zip";
	private static final String JPG_FILE = "D:/zsl/1.jpg";
	private static final String FILE_NAME = "1.jpg";
	
	public static void zipFileNoBuffer() {
	    File zipFile = new File(ZIP_FILE);
	    try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); WritableByteChannel writableByteChannel = Channels.newChannel(zipOut)) {
	        //开始时间
	        long beginTime = System.currentTimeMillis();

	        //内存中的映射文件
	        try (FileChannel fileChannel = new RandomAccessFile(JPG_FILE, "r").getChannel()) {
	        	zipOut.putNextEntry(new ZipEntry(FILE_NAME));
	        	MappedByteBuffer mappedByteBuffer = new RandomAccessFile(JPG_FILE, "r").getChannel().map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
	        	writableByteChannel.write(mappedByteBuffer);
            }
	        long endTime = System.currentTimeMillis();
	        System.out.println(endTime - beginTime);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	public static void main(String[] args) {
		zipFileNoBuffer();
	}

}
